<?php
namespace model;

use yii\base\ErrorException;
class model{
    protected static $pdobject='';
    private $classtable="";
    public $table="";
    private $db='';
    protected $sql="";

    private function __construct($dsn, $username, $passwd)  //构造pdo并把它赋值给$this->db对象
    {
        try{
            $this->db=new \PDO($dsn, $username, $passwd);
            $this->db->query("set names utf8");
            return $this->db;
        }catch (PDOException $e){
            return  $e->getMessage();
        }
    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    public static function getobject(){//获取对象
        $dbconfig=include('config/config.php');
        extract($dbconfig);
        $dsn=$db['dsn'].";dbname=".$db['table'];
        $username=$db['user'];
        $passwd=$db['password'];
        if(static::$pdobject){
            return static::$pdobject;
        }else{
            static::$pdobject=new static($dsn,$username,$passwd);
            return static::$pdobject;
        }
    }

    public function mquery($table,$value){
        $sql="select ".$value." from ".$table;
        return $this->db->query($sql);
    }


    public function insertquery($table,$key,$value){
        $sql="insert into `".$table."` (".$key.") values ('".$value."')";
        try{
            return $this->db->exec($sql);
        }catch (PDOException $e){
            return  $e->getMessage();
        }

    }

    public function fromtable($table){
        $this->sql.=" from ".$table;
        return $this;
    }
    public function wheres($where=''){
        if(is_array($where))
        {
            foreach($where as $key=>$val){
                $sql=$key."=".$val." ";
            }
            $this->sql.=" where ".$sql;
        }else{
            if($where==''){
                $this->sql.=" where 1";
            }else{
                $this->sql.=" where ".$where;
            }
        }



        return $this;
    }

    public function selects($something){
        $this->sql.=" select ".$something;
        return $this;
    }
    public function all(){
       return  $this->db->query($this->sql);
    }

    public function delete($something=''){
        if($something==''){
            return false;
        }
        if(is_array($something)){
            foreach ($something as $key=>$val){
                $sql=$key."=".$val;
            }
        }else{
            $sql=$something;
        }
        $sqls='delete from '.$this->table." where ".$sql;
        return $this->db->exec($sqls);
    }

}
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/2
 * Time: 9:19
 */